#!/usr/bin/env bash

if [ -z "$1" ]; then
    echo "Usage: $0 input.mp4"
    exit 1
fi

INPUT="$1"
DURATION=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$INPUT")
DURATION=${DURATION%.*}
SEG_LENGTH=240
FULL_SEGMENTS=$(( DURATION / SEG_LENGTH ))
REMAINDER=$(( DURATION % SEG_LENGTH ))

if [ "$REMAINDER" -gt 0 ]; then
    TOTAL_SEGMENTS=$(( FULL_SEGMENTS + 1 ))
else
    TOTAL_SEGMENTS=$FULL_SEGMENTS
fi

START_TIME=0
COUNTER=1

while [ $COUNTER -le $FULL_SEGMENTS ]; do
    OUTPUT_FILE=$(printf "output_%03d.mp4" $COUNTER)
    ffmpeg -y -i "$INPUT" -ss $START_TIME -t $SEG_LENGTH -c copy "$OUTPUT_FILE"
    START_TIME=$(( START_TIME + SEG_LENGTH ))
    COUNTER=$(( COUNTER + 1 ))
done

if [ "$REMAINDER" -gt 0 ]; then
    OUTPUT_FILE=$(printf "output_%03d.mp4" $COUNTER)
    ffmpeg -y -i "$INPUT" -ss $START_TIME -t $REMAINDER -c copy "$OUTPUT_FILE"
fi

echo "Done. Created $TOTAL_SEGMENTS segments."